var request = (function () {
    var Request = function () {}

    Request.prototype.send = function (options) {
        options = options || {};
        // 发送请求URL
        var url = options.url;
        // 请求类型
        var type = (options.type || 'GET').toUpperCase();
        // 数据
        var data = options.data
        // headers
        var headers = options.headers

        var responseType = options.responseType

        // 创建xhr对象
        var xhr
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            // 兼容低版本IE 10以下
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        xhr.open(type, url, true);

        if (headers) {
            Object.keys(headers).forEach(key => {
                xhr.setRequestHeaders(key, headers[key])
            })
        }


        if (responseType) {
            xhr.responseType = responseType
        }

        xhr.send(data);

        // 接收
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var status = xhr.status;
                if (status === 200) {
                    options.success && options.success(responseType? this.response:xhr.responseText);

                } else {
                    options.error && options.error(xhr);
                }
            }
        }

        xhr.onerror = function () {
            options.error && options.error(Error('There was a network error.'))
        }
    }

    // 单例
    if (Request.flag)  return Request.flag;
    Request.flag = new Request();
    return Request.flag;
    
})()

// promise方式
var fetch = function (method, url, data) {
    return new Promise((resolve, reject) => {
      request.send({
        type: method,
        url,
        data,
        success: function (json) {
          resolve(json)
        },
        error: function (err) {
          reject(err)
        }
      })
    })
  }


  // 根据url下载文件
  var downloadFile = function (url) {
      return new Promise((resolve, reject) => {
          request.send({
              type: 'get',
              url,
              responseType: 'blob',
              success: function (data) {
                resolve(data)
              },
              error: function (err) {
                reject(err)
              }
          })
      })
  }